/*
 * Copyright (C), 2002-2018, 你的兔宝宝电子商务有限公司
 * FileName: CURL.java
 * Author:   你的兔宝宝
 * Date:     2018-2-13 下午4:22:43
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.baby.demo.utils.net;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Properties;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baby.demo.utils.Strings;

/**
 * 〈一句话功能简述〉<br> 
 * 〈功能详细描述〉
 *
 * @author 你的兔宝宝
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class CURL {
    
    private static final Logger logger = LoggerFactory.getLogger(CURL.class);
    
    /**
     * 
     * 功能描述: https设置<br>
     * 〈功能详细描述〉
     *
     * @param conn
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @Author:   你的兔宝宝
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    void httpsConnection(URLConnection conn) throws NoSuchAlgorithmException, KeyManagementException{
        TrustManager[] tm = { new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }
            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }
        }};  
        SSLContext sslContext = SSLContext.getInstance("SSLv3");  
        sslContext.init(null, tm, new java.security.SecureRandom());  
        SSLSocketFactory ssf = sslContext.getSocketFactory();  
        HttpsURLConnection httpsconn = (HttpsURLConnection)conn;
        httpsconn.setSSLSocketFactory(ssf);
        httpsconn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
    }
    
    /**
     * 
     * 功能描述: url2string<br>
     * 〈功能详细描述〉
     *
     * @param url
     * @return
     * @throws Exception 
     * @Author:   你的兔宝宝
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public String curl(String url) throws RuntimeException{
        try {
            URL uri = new URL(url);
            String protocol = uri.getProtocol();
            String stream = Strings.EMPTY;
            if ("http".equalsIgnoreCase(protocol) || "https".equalsIgnoreCase(protocol)) {
                URLConnection conn = uri.openConnection();
                conn.setConnectTimeout(2000);
                conn.setReadTimeout(10000);
                if("https".equalsIgnoreCase(protocol)){
                    httpsConnection(conn);
                }
                stream = IOUtils.toString(conn.getInputStream(), "utf-8");
            }else{
                stream = IOUtils.toString(uri, "utf-8");
            }
            return stream;
        } catch (Exception e) {
            logger.error("读取url出错"+url);
            throw new RuntimeException("网络异常",e);
        }
    }
    
    /**
     * 
     * 功能描述: url2file<br>
     * 〈功能详细描述〉
     *
     * @param url
     * @param filepath
     * @throws Exception 
     * @Author:   你的兔宝宝
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public void curl(String url,String filepath) throws RuntimeException{
        try {
            File file = new File(filepath);
            if (!file.exists()) {
                FileUtils.touch(file);
            }
            byte[] bs = null;
            URL uri = new URL(url);
            String protocol = uri.getProtocol();
            if ("http".equalsIgnoreCase(protocol) || "https".equalsIgnoreCase(protocol)) {
                URLConnection conn = uri.openConnection();
                conn.setConnectTimeout(2000);
                conn.setReadTimeout(10000);
                if("https".equalsIgnoreCase(protocol)){
                    httpsConnection(conn);
                }
                bs = IOUtils.toByteArray(conn.getInputStream());
            }else{
                bs = IOUtils.toByteArray(new URL(url).openStream());
            }
            if( bs != null ){
                IOUtils.write(bs, new FileOutputStream(file));
            }
        } catch (Exception e) {
            logger.error("读取url出错"+url);
            throw new RuntimeException("网络异常",e);
        }
    }
    
    public void proxy(String host,String port){
        Properties prop = System.getProperties();
        // 设置http访问要使用的代理服务器的地址        
        prop.setProperty("http.proxyHost", host);
        // 设置http访问要使用的代理服务器的端口        
        prop.setProperty("http.proxyPort", port);
        
        // 设置https访问要使用的代理服务器的地址        
        prop.setProperty("https.proxyHost", host);
        // 设置http访问要使用的代理服务器的端口        
        prop.setProperty("https.proxyPort", port);
    }
}
